package xyz.xtt.pay.mq;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.pay.service.INftOrderService;
import xyz.xtt.pay.vo.PayCallbackMessage;

/**
 * 统一支付回调
 *
 * @author dale
 * @since 2024/12/30
 **/
@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "pay_callback_topic", consumerGroup = "${rocketmq.consumer.group.paycallback}")
public class PayCallbackConsumer implements RocketMQListener<String> {
    private static final String NFT_ORDER_PREFIX = "NFT_";
    @Autowired
    private INftOrderService nftOrderService;

    @Override
    public void onMessage(String message) {
        if (StringUtils.isEmpty(message)) {
            return;
        }else if (!JSONUtil.isTypeJSON(message)) {
            log.warn("PayCallbackConsumer Received message: {} is not json", message);
            return;
        }

        try {
            PayCallbackMessage callbackMessage = JSONUtil.toBean(message, PayCallbackMessage.class);
            if (Objects.isNull(callbackMessage)) {
                log.warn("PayCallbackConsumer JSONUtil.toBean is null. message:{}", message);
                return;
            } else if (!callbackMessage.getOrderNo().startsWith(NFT_ORDER_PREFIX)
                    || !callbackMessage.getTradeNo().startsWith(NFT_ORDER_PREFIX)) {
                //非NFT订单无需处理
                return;
            }
            log.info("PayCallbackConsumer Received nft order message: {}", message);

            callbackMessage.setOrderNo(callbackMessage.getOrderNo().substring(NFT_ORDER_PREFIX.length()));
            callbackMessage.setTradeNo(callbackMessage.getTradeNo().substring(NFT_ORDER_PREFIX.length()));
            nftOrderService.payCallbackConsume(callbackMessage,false);
        } catch (Exception e) {
            log.info("PayCallbackConsumer consume failed. message:{} ex:{}", message, e.getMessage(), e);
            throw new RuntimeException("PayCallbackConsumer Consumer Message exception", e);
        }
    }
}
